<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class ConsultController extends Controller
{
    //咨询管理首页
    public function index()
    {
    	// 获取咨询列表
    	for ($i=0; $i <=3 ; $i++) { 
    		$list[] = DB::table('consult')
    		  ->join('storeuser','storeuser.userId','consult.uid')
    		  ->join('goods','goods.id','consult.gid')
    		  ->select('consult.*','storeuser.userName','goods.name')
    		  ->where('coType',$i)
    		  ->get();
                       
    	}
         
    	// dd($list);
    	return view('admin.consult.index',['list' => $list]);
    }

    //删除咨询
    public function delConsult($id)
    {
    	$row = DB::table('consult')->where('consultId',$id)->delete();
    	if ( $row > 0 ) {
    		$ob = DB::table('consultRe')->where('coReCid',$id)->first();
    		
    		if ( $ob != null) {

    			$rows = DB::table('consultRe')->where('coReCid',$id)->delete();
    			return back()->with('msg','删除成功');
    		}
    		return back()->with('msg','删除成功');
    	}

    }

    //咨询回复详情页
    public function consultRe($id)
    {		
    	$list = DB::table('consult')
    		  ->join('storeuser','storeuser.userId','consult.uid')
    		  ->join('goods','goods.id','consult.gid')
    		  ->select('consult.*','storeuser.userName','goods.name')
    		  ->where('consultId',$id)
              
    		  ->get();
    	
    	$ob = DB::table('consultre')
    		  ->join('storeadmin','storeadmin.adminId','consultre.coReUid')
    		  ->select('consultre.*','storeadmin.adminName')
    		  ->where('consultre.coReCid',$id)
    		  ->get();
    	// dd($ob);
    	return  view('admin.consult.consultRe',['list' => $list ,'ob' => $ob ]);
    }


    //管理员回复
    public function doConsultRe(Request $request)
    {
    	//获取提交数据
    	$data = $request->except('_token');

    	//获取回复人
    	$data['coReUid'] = session('adminUser')['adminId'];

    	//获取时间戳
    	$data['coReTime'] = time();

    	//自定义验证信息
    	$message = [
    		'required' => '回复内容不能为空',
    	];
  
  		//设置验证规则
  		$this -> validate($request,[

  			'coReContent' => 'required',

  			],$message);
    	//写入数据
    	$row = DB::table('consultre')->insertGetId($data);
    	
    	if ( $row > 0 ) {

    		DB::table('consult')->where('consultId',$data['coReCid'])->update(['coStatu' => 1]);
    		return back()->with('msg','回复成功');
    	} 
    }

    //管理员回复删除
    public function delConsultRe($id)
    {
    	$row = DB::table('consultre')->where('consultReId',$id)->delete();
    	if ( $row ) {

    		return back()->with('msg','删除回复成功');
    	}
    	
    }
}
